<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="120px"
    class="w-full"
  >
    <el-form-item label="频道名称" prop="name" required>
      <el-input v-model="newFormInline.name" placeholder="请输入频道名称" />
    </el-form-item>
    <el-form-item label="限制类型" prop="restriction" required>
      <el-select
        v-model="newFormInline.restriction"
        placeholder="请选择限制类型"
      >
        <el-option label="无限制" :value="0" />
        <el-option label="只允许固定成员进入" :value="1" />
        <el-option label="仅区内用户" :value="2" />
        <el-option label="仅域内" :value="3" />
        <el-option label="限制进入的最小权限" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="所属区域" prop="zoneId">
      <el-cascader
        v-model="newFormInline.zoneId"
        class="w-full"
        :options="parentOptions"
        :props="cascaderProps"
        placeholder="请选择区域"
        clearable
      />
    </el-form-item>
    <el-form-item label="备注" prop="comment">
      <el-input
        v-model="newFormInline.comment"
        type="textarea"
        :maxlength="200"
        show-word-limit
        :rows="4"
        placeholder="请输入备注，最多200字"
      />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { FormProps } from "../componentsUtils/type/channelTypes";
import { formRules } from "../componentsUtils/rule/channelRules";
import { ElMessage } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { handleTree } from "@/utils/tree";
const props = withDefaults(
  defineProps<
    FormProps & {
      title?: string;
    }
  >(),
  {
    formInline: () => ({
      id: 0,
      no: 0,
      name: "",
      dealerId: 0,
      tenantId: 0,
      zoneId: 0,
      restriction: 0,
      powerLimit1: 0,
      powerLimit2: 0,
      pttMode: 0,
      maxLimit: 0,
      canMonitor: true,
      encoding: 0,
      encodingRate: 0,
      encodingBit: 0,
      comment: ""
    }),
    title: ""
  }
);

const newFormInline = ref(props.formInline);
const ruleFormRef = ref();
const parentOptions = ref<any[]>([]);
const loading = ref(false);

// 级联选择器属性配置
const cascaderProps = {
  value: "Id",
  label: "Name",
  children: "children",
  emitPath: false, // 只返回最后一级的ID
  checkStrictly: true // 允许选择任意一级
};

// 监听props.formInline的变化，同步到newFormInline
watch(
  () => props.formInline,
  newValue => {
    newFormInline.value = { ...newValue };
  },
  { deep: true }
);

// 获取区域列表函数
function getZoneList(): Promise<void> {
  return new Promise(resolve => {
    loading.value = true;
    http
      .get(changeHttpLink("/api/Zone/select"), {
        params: {
          tenantId: newFormInline.value.tenantId
        }
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          // 转换为树形结构
          parentOptions.value = handleTree(
            res.Data || [],
            "Id",
            "ParentZoneId",
            "children"
          );
          console.log("格式化后的区域树形数据:", parentOptions.value);
        } else {
          console.error("获取区域列表失败:", res?.Message || "未知错误");
          ElMessage.error(res?.Message || "获取区域列表失败");
        }
        resolve();
      })
      .catch(err => {
        loading.value = false;
        console.error("获取区域列表失败:", err.message);
        ElMessage.error("获取区域列表失败");
        resolve();
      });
  });
}

// 判断是否为新增场景
const isAdd = computed(() => newFormInline.value.id === 0);

// 添加获取表单数据的方法
function getFormData() {
  return newFormInline.value;
}

// 组件挂载时，获取频道号和区域列表
onMounted(() => {
  // 获取区域列表
  getZoneList();

  // 如果是新增场景则获取频道号
  if (isAdd.value && props.title !== "修改") {
    http
      .get(changeHttpLink("/api/Channel/channel_no"))
      .then((res: any) => {
        if (res.Success) {
          newFormInline.value.no = res.Data.no;
        } else {
          ElMessage.error(res.Message);
        }
      })
      .catch(err => {
        ElMessage.error(err.message);
      });
  }
});

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef, getFormData });
</script>
